<template>
  <GlobalHeader></GlobalHeader>
  <v-app>
    <v-main>
      <v-container style="max-width: 1900px; min-height: 400px;">
        <ProcessFlow></ProcessFlow>
        <v-card>
          <v-card-text>
            <v-row class="mb-4">
              <v-col cols="12">
                <v-select v-model="selectedDevice" :items="deviceModels" label="选择设备型号" item-title="modelName"
                          item-value="modelName" @update:modelValue="handleDeviceSelection" return-object clearable
                          required>
                  <template v-slot:item="{ props, item }">
                    <v-list-item
                        v-bind="props"
                        :title="item.raw.modelName"
                        :subtitle="`原价值: ${item.raw.initialValue} 元`"
                    ></v-list-item>
                  </template>
                  <template v-slot:selection="{ item }">
                    <span>{{ item.raw.modelName }} (原价值: {{ item.raw.initialValue }} 元)</span>
                  </template>
                </v-select>
              </v-col>
            </v-row>
            <router-link to="/batch-evaluate">
              <v-btn style="background-color: dodgerblue;margin-left: 1500px;">批量评估</v-btn>
            </router-link>
            <v-row class="indicator-row">
              <v-col
                  v-for="(primaryIndicator, primaryIndex) in Object.keys(primaryIndicatorWeights)"
                  :key="primaryIndex"
                  cols="12"
                  md="4"
                  class="mb-4"
              >
                <v-card class="indicator-card">
                  <v-card-title class="text-center" style="font-size: 40px; font-weight: 600; color: #4a90e2">
                    {{ primaryIndicator }}
                  </v-card-title>
                  <v-card-text>
                    <div
                        v-for="(indicator, index) in secondaryIndicators.filter(item => item.primaryIndicator === primaryIndicator)"
                        :key="index" class="mb-2">
                      <v-row align="center">
                        <v-col cols="5" :class="{'error-label': validationErrors[indicator.name]}">
                          <label :for="indicator.name">{{ indicator.name }}</label>
                        </v-col>
                        <v-col cols="6">
                          <v-text-field
                              :id="indicator.name"
                              v-model="scores[indicator.name]"
                              :hint="indicator.explanation + ' 评价分: ' + indicator.evaluationRange + (indicator.unit ? ' 单位: ' + indicator.unit : '')"
                              type="number"
                              :min="indicator.min"
                              :max="indicator.max"
                              required
                              dense
                              hide-details="auto"
                              @blur="validateScore(indicator)"
                              :class="{'error-input': validationErrors[indicator.name]}"
                          ></v-text-field>
                          <div v-if="validationErrors[indicator.name]" class="error-message">
                            {{ validationErrors[indicator.name] }}
                          </div>
                        </v-col>
                      </v-row>
                    </div>
                  </v-card-text>
                </v-card>
              </v-col>
            </v-row>

            <v-btn color="primary" @click="startEvaluation" :disabled="hasValidationErrors || isLoading">一键评估</v-btn>

            <v-dialog v-model="showProgressDialog" persistent width="400">
              <v-card class="progress-dialog">
                <v-card-title class="text-h6 text-center">评估中...</v-card-title>
                <v-card-text class="mt-4">
                  <div class="modern-progress-container">
                    <div class="progress-bar-modern">
                      <div class="progress-fill-modern" :style="{ width: progress + '%' }">
                        <div class="loading-spinner" :style="{ left: `calc(${progress}% - 20px)` }">
                          <div class="spinner-dot"></div>
                          <div class="spinner-dot"></div>
                          <div class="spinner-dot"></div>
                        </div>
                      </div>
                    </div>
                    <div class="progress-text-modern">{{ Math.round(progress) }}%</div>
                  </div>
                </v-card-text>
              </v-card>
            </v-dialog>

            <div v-if="totalScore !== null" class="mt-6">
              <v-card>
                <v-card-title style="font-size: 40px; font-weight: 600; color: #4a90e2">评估结果</v-card-title>
                <v-card-text>
                  <v-row justify="space-around" class="mb-4">
                    <v-col cols="12" md="auto" class="text-center">
                      <div class="text-subtitle-1">总得分</div>
                      <strong class="text-h4">{{ totalScore ? totalScore.toFixed(4) : '-' }}</strong>
                    </v-col>
                    <v-col cols="12" md="auto" class="text-center">
                      <div class="text-subtitle-1">评估等级</div>
                      <strong class="text-h4" :style="gradeStyle">{{ grade }}</strong>
                    </v-col>
                    <v-col cols="12" md="auto" class="text-center">
                      <div class="text-subtitle-1">评估价值</div>
                      <strong class="text-h4">{{ finalRealPrice !== null ? finalRealPrice.toFixed(2) : '-' }} 元</strong>
                    </v-col>
                  </v-row>
                  <div v-if="grade === '建议报废'" class="text-center mb-4" style="color: black;">建议报废</div>
                  <v-expansion-panels>
                    <v-expansion-panel
                        v-for="(primaryIndicator) in Object.keys(primaryIndicatorWeights)"
                        :key="primaryIndicator"
                    >
                      <v-expansion-panel-title style="color: #4a90e2; font-size: 25px">{{
                          primaryIndicator
                        }}
                      </v-expansion-panel-title>
                      <v-expansion-panel-text>
                        <v-list dense>
                          <v-list-item
                              v-for="(indicator, index) in filteredSecondaryIndicators(primaryIndicator)"
                              :key="index"
                          >
                            <template v-slot:title>
                              {{ indicator.name }}
                            </template>
                            <template v-slot:subtitle>
                              评估值:
                              {{ normalizedValues[indicator.name] ? normalizedValues[indicator.name].toFixed(4) : '-' }}
                              <span class="ml-2">加权得分: {{
                                  weightedScores[indicator.name] ? weightedScores[indicator.name].toFixed(4) : '-'
                                }}</span>
                            </template>
                          </v-list-item>
                        </v-list>
                      </v-expansion-panel-text>
                    </v-expansion-panel>
                  </v-expansion-panels>
                </v-card-text>
                <v-card-actions class="justify-end">
                  <v-btn color="success" @click="generateReport" :disabled="totalScore === null">生成报告</v-btn>

                </v-card-actions>
              </v-card>
            </div>

            <v-dialog v-model="reportDialog" persistent width="80%">
              <v-card>
                <v-card-title>
                  评估报告
                  <v-spacer></v-spacer>
                  <v-btn color="primary" @click="exportPdf">导出 PDF</v-btn>
                  <v-btn @click="reportDialog = false">关闭</v-btn>
                </v-card-title>
                <v-card-text id="report-content" class="py-4" style="position: relative;">
                  <div
                      style="position: absolute; top: 10px; right: 10px; display: flex; flex-direction: column; align-items: flex-end;">
                    <div style="font-size: 0.8em; color: #777; margin-bottom: 5px;">
                      报告编码: {{ reportCode }}
                    </div>
                    <div v-if="grade" :class="['grade-badge', gradeColorClass]">
                      {{ grade === '建议报废' ? '报废' : grade }}
                    </div>
                  </div>
                  <h1>电力装备剩余价值评估报告</h1>
                  <p>生成时间: {{ new Date().toLocaleString() }}</p>
                  <p><b>设备型号:</b> {{ selectedDevice ? selectedDevice.modelName : '-' }}</p>
                  <p><b>设备原价值:</b> {{ originalPrice ? originalPrice.toFixed(2) : '-' }} 元</p>
                  <v-divider class="my-2"></v-divider>
                  <h2>指标评估明细</h2>
                  <v-table density="compact">
                    <thead>
                    <tr>
                      <th>一级指标</th>
                      <th>指标名称</th>
                      <th>测定值</th>
                      <th>单位</th>
                      <th>评估值</th>
                      <th>一级权重</th>
                      <th>二级权重</th>
                      <th>加权权重</th>
                      <th>加权得分</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(indicator, index) in secondaryIndicators" :key="index">
                      <td>{{ indicator.primaryIndicator }}</td>
                      <td>{{ indicator.name }}</td>
                      <td>{{ scores[indicator.name] ?? '-' }}</td>
                      <td>{{ indicator.unit || '分' }}</td>
                      <td>{{ normalizedValues[indicator.name]?.toFixed(4) || '-' }}</td>
                      <td>{{ primaryIndicatorWeights[indicator.primaryIndicator]?.toFixed(4) }}</td>
                      <td>{{ indicator.weight?.toFixed(4) }}</td>
                      <td>{{ indicator.weightedWeight?.toFixed(4) || '-' }}</td>
                      <td>{{ weightedScores[indicator.name]?.toFixed(4) || '-' }}</td>
                    </tr>
                    </tbody>
                  </v-table>
                  <v-divider class="my-2"></v-divider>
                  <h2>总得分与评估价值</h2>
                  <p><b>总得分:</b> {{ totalScore ? totalScore.toFixed(2) : '-' }}</p>
                  <p class="text-h5">
                    装备状态: <span :style="gradeStyle">{{ grade }}</span>
                  </p>
                  <p v-if="grade === '建议报废'" class="text-h5" style="color: black;">装备状态: {{ grade }}</p>
                  <h2>装备剩余价值</h2>
                  <p class="text-h5"><b>装备剩余价值:</b> {{ finalRealPrice !== null ? finalRealPrice.toFixed(2) : '-' }}</p>
                </v-card-text>
              </v-card>
            </v-dialog>
          </v-card-text>
        </v-card>
      </v-container>
    </v-main>
    <AppFooter class="app-footer"/>
  </v-app>
</template>

<script>
// --- SCRIPT SECTION IS UNCHANGED ---
import {jsPDF} from 'jspdf';
import 'jspdf-autotable';
import axios from 'axios';
import AppFooter from '@/components/Footer/AppFooter.vue';
import ProcessFlow from "@/components/Calculate/ProcessFlow.vue";
import GlobalHeader from "@/components/Index/GlobalHeader.vue";
import {computed} from "vue";


const isLoggedIn = computed(() => {
  return localStorage.getItem('admin-token') !== null;
});

export default {
  components: {GlobalHeader, ProcessFlow, AppFooter},
  data() {
    return {
      primaryIndicatorWeights: {
        '基础检查': 0.2453,
        '运行性能': 0.4299,
        '品牌声誉': 0.3248,
      }, // 一级指标
      secondaryIndicators: [], //二级指标
      scores: {}, //分数
      totalScore: null, //总分
      grade: null, //等级
      finalRealPrice: null, //最终实际价格
      finalValuation: null, //最终估值
      reportDialog: false, //报告弹窗
      gradeColors: {
        'A': 'green', 'B': 'green', 'C': 'orange', 'D': 'orange', 'E': 'red', 'F': 'red', '建议报废': 'black',
      }, //等级颜色
      reportCode: '', //报告编号
      deviceModels: [], //设备型号
      selectedDevice: null, //选择设备
      normalizedValues: {}, //归一化值
      weightedScores: {}, //加权分数
      validationRules: {
        B1: {min: 0, max: 100},
        B2: {min: 0, max: 100},
        B3: {min: 0, max: 100},
        B4: {min: 0, max: 100},
        B5: {min: 0, max: 100},
        B6: {min: 0, max: 20},
        B7: {min: 0, max: 10},
        B8: {min: 0, max: 20},
        B9: {min: 0, max: 100},
        B10: {min: 0, max: 100},
      }, //验证规则
      validationErrors: {}, //验证错误
      showProgressDialog: false, //显示进度弹窗
      progress: 0, //进度
      isLoading: false, //正在加载
      historyRecords: [],
      userId: 1 // 临时写死，正式可从登录用户中拿
    };
  },

  computed: { //里面存放对象
    // computed中的函数 依赖的值未变 不会调用
    originalPrice() {
      return this.selectedDevice ? parseFloat(this.selectedDevice.initialValue) : null;

    },
    gradeStyle() {
      const color = this.gradeColors[this.grade] || 'black';
      return {color};
    },
    gradeColorClass() {
      if (this.grade === 'A') return 'grade-a';
      if (this.grade === 'B') return 'grade-b';
      if (this.grade === 'C') return 'grade-c';
      if (this.grade === 'D') return 'grade-d';
      if (this.grade === 'E') return 'grade-e';
      if (this.grade === 'F') return 'grade-f';
      if (this.grade === '建议报废') return 'grade-scrap';
      return '';
    },
    //存在验证错误
    hasValidationErrors() {
      //Object.keys方法返回：对象中所有键组成的一个数组。length计算变量长度
      return Object.keys(this.validationErrors).length > 0;
    },
  },
  async mounted() {
    this.fetchDeviceModels();
    this.fetchSecondaryIndicators();

  },
  methods: {

    //重置计算结果
    resetCalculationResults() {
      this.totalScore = null;
      this.grade = null;
      this.finalValuation = null;
      this.finalRealPrice = null;
      this.normalizedValues = {};
      this.weightedScores = {};
      this.validationErrors = {};
      this.showProgressDialog = false;
      this.progress = 0;
      this.isLoading = false;
    },
    //设备的选择
    handleDeviceSelection() {
      this.resetCalculationResults();
    },
    // 验证指标

    validateScore(indicator) {

      const value = parseFloat(this.scores[indicator.name]); //parseFloat遇到不能识别为数字的字符就会停止解析

      const min = indicator.min;
      const max = indicator.max;

      if (min !== null && max !== null && !isNaN(value)) {

        if (value < min || value > max) {
          this.validationErrors[indicator.name] = `请输入数值在 ${min} 到 ${max} 之间的值`;
        } else {
          delete this.validationErrors[indicator.name];
        }
      } else if (isNaN(value) && this.scores[indicator.name] !== '' && this.scores[indicator.name] !== null) {
        this.validationErrors[indicator.name] = '请输入有效的数值';
      } else {
        delete this.validationErrors[indicator.name];
      }
    },
    //计算得分
    async calculateScore() {
      const requestData = {
        scores: this.scores,
        secondaryIndicators: this.secondaryIndicators,
        originalPrice: this.originalPrice,
        primaryIndicatorWeights: this.primaryIndicatorWeights,
      };
      try {
        const response = await axios.post('/api/evaluation/calculate', requestData);
        return {
          normalizedValues: response.data.normalizedValues,
          weightedScores: response.data.weightedScores,
          totalScore: response.data.totalScore,
          grade: response.data.grade,
          finalValuation: response.data.finalValuation,
          finalRealPrice: response.data.finalRealPrice,
          updatedIndicators: response.data.updatedIndicators,
        };
      } catch (error) {
        console.error('评估计算失败:', error.response?.data || error.message);
        throw new Error(`评估计算失败: ${error.response?.data?.message || '请检查输入或联系管理员。'}`);
      }
    },
    //开始评估
    async startEvaluation() {


      //null或undefined时为true
      if (!this.selectedDevice) {
        alert('请先选择一个设备型号。');
        return;
      }

      if (this.hasValidationErrors) { //如果存在键
        let errorMessage = '请检查以下指标的输入值是否在有效范围内：\n';
        for (const indicatorName in this.validationErrors) {
          errorMessage += `- ${indicatorName}: ${this.validationErrors[indicatorName]}\n`;
        }
        alert(errorMessage);
        return;
      }
      // 提取所有name存储到requiredIndicators
      const requiredIndicators = this.secondaryIndicators.map(i => i.name);
      //确保所有字段都被赋值
      const missingScores = requiredIndicators.filter(name => !(name in this.scores && this.scores[name] !== null && this.scores[name] !== ''));
      if (missingScores.length > 0) {
        alert(`请输入以下指标的测定值: ${missingScores.join(', ')}`);
        return;
      }

      this.showProgressDialog = true;
      this.progress = 0;
      this.isLoading = true;

      const intervalDuration = 25; // Keep smooth animation interval
      const totalTime = 1000;
      const steps = totalTime / intervalDuration;
      const increment = 100 / steps;
      let currentProgress = 0;

      const progressInterval = setInterval(() => {
        currentProgress += increment;
        this.progress = Math.min(100, currentProgress);
        if (this.progress >= 100) {
          clearInterval(progressInterval);
          setTimeout(async () => {
            try {
              const result = await this.calculateScore();

              this.normalizedValues = result.normalizedValues;
              this.weightedScores = result.weightedScores;
              this.totalScore = result.totalScore;
              this.grade = result.grade;
              this.finalValuation = result.finalValuation;
              this.finalRealPrice = result.finalRealPrice;

              if (result.updatedIndicators) {
                this.secondaryIndicators = result.updatedIndicators;
              }
            } catch (error) {
              console.error('评估出错:', error);
              alert(error.message);
            } finally {
              this.showProgressDialog = false;
              this.isLoading = false;
            }
          }, 300); // Keep slight delay
        }
      }, intervalDuration);

    },
    //获取设备型号
    async fetchDeviceModels() {
      try {
        const response = await axios.get('/api/device-models');
        this.deviceModels = response.data;
        console.log('Fetched device models:', this.deviceModels);
      } catch (error) {
        console.error('获取设备型号列表失败:', error);
        this.deviceModels = [];
        alert('无法加载设备型号列表，请稍后重试或联系管理员。');
      }
    },
    //获取次要指标
    async fetchSecondaryIndicators() {
      try {
        const response = await axios.get('/api/secondary-indicators');
        this.secondaryIndicators = response.data.secondaryIndicators;
        this.secondaryIndicators.forEach(indicator => {
          const primaryWeight = this.primaryIndicatorWeights[indicator.primaryIndicator];
          if (primaryWeight && indicator.weight && !indicator.weightedWeight) {
            indicator.weightedWeight = primaryWeight * indicator.weight;
          }
          const match = indicator.name.match(/\((B\d+)\)/);
          if (match) {
            const key = match[1];
            if (this.validationRules[key]) {
              indicator.min = this.validationRules[key].min;
              indicator.max = this.validationRules[key].max;
            } else {
              indicator.min = null;
              indicator.max = null;
              console.warn(`未在 validationRules 中找到 ${key} 的规则`);
            }
          } else {
            indicator.min = null;
            indicator.max = null;
            console.warn(`无法从 ${indicator.name} 中提取指标标识符`);
          }
        });
        console.log('Fetched secondary indicators:', this.secondaryIndicators);
      } catch (error) {
        console.error('获取评估指标列表失败:', error);
        this.secondaryIndicators = [];
        alert('无法加载评估指标列表，请稍后重试或联系管理员。');
      }
    },
    //生成报告
    generateReport() {
      if (this.totalScore === null) {
        alert('请先计算评估值再生成报告。');
        return;
      }
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const random = String(Math.floor(Math.random() * 10000)).padStart(4, '0');
      this.reportCode = `REPORT-${year}${month}${day}-${random}`;
      this.reportDialog = true;
    },
    //导出报告
    async exportPdf() {
      const pdf = new jsPDF('p', 'mm', 'a4');
      const reportTitle = '电力装备剩余价值评估报告';
      const generationTime = `生成时间: ${new Date().toLocaleString()}`;
      const reportCodeText = `报告编码: ${this.reportCode}`;
      const deviceModelText = `设备型号: ${this.selectedDevice ? this.selectedDevice.modelName : '-'}`;
      const originalPriceText = `设备原价值: ${this.originalPrice ? this.originalPrice.toFixed(2) : '-'} 元`;
      let startY = 15;

      try {
        const fontUrl = '/fonts/simhei.ttf';
        const response = await fetch(fontUrl);
        if (!response.ok) {
          throw new Error(`Failed to fetch font: ${response.statusText}`);
        }
        const fontBlob = await response.blob();
        const reader = new FileReader();
        const base64Font = await new Promise((resolve, reject) => {
          reader.onloadend = () => {
            const base64Data = reader.result.split(',')[1];
            resolve(base64Data);
          };
          reader.onerror = reject;
          reader.readAsDataURL(fontBlob);
        });
        pdf.addFileToVFS('simhei.ttf', base64Font);
        pdf.addFont('simhei.ttf', 'simhei', 'normal');
        pdf.setFont('simhei');
        pdf.setTextColor(0); // 设置文本颜色为黑色

        // --- 添加第一页 (封面 - 文本绘制) ---

        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();

// 智能评估师 (顶部居中)
        pdf.setFontSize(36);
        pdf.text('智能评估师', pageWidth / 2, 60, {align: 'center'}); // 稍微下移一点

// 电力装备剩余价值评估报告 (垂直居中)
        pdf.setFontSize(24);
        const verticalText = ['电', '力', '装', '备', '剩', '余', '价', '值', '评', '估', '报', '告'];
        const verticalTextHeight = verticalText.length * 10; // 计算垂直文本总高度
        const startYVertical = pageHeight / 2 - verticalTextHeight / 2;
        const startXVertical = pageWidth / 2; // 微调水平位置
        verticalText.forEach((char, index) => {
          pdf.text(char, startXVertical, startYVertical + index * 10, {align: 'center'});
        });

// 智能评估师 Logo (底部居中)
        const logoImageUrl = '/src/assets/images/Index/img.png'; // 替换为您的Logo图片路径
        const logoResponse = await fetch(logoImageUrl);
        if (!logoResponse.ok) {
          console.warn(`Failed to fetch logo image: ${logoResponse.statusText}`);
        } else {
          const logoBlob = await logoResponse.blob();
          const readerLogo = new FileReader();
          const base64Logo = await new Promise((resolve, reject) => {
            readerLogo.onloadend = () => {
              const base64Data = readerLogo.result.split(',')[1];
              resolve(base64Data);
            };
            readerLogo.onerror = reject;
            readerLogo.readAsDataURL(logoBlob);
          });
          const logoWidth = 60; // mm
          const logoHeight = 20; // mm
          const logoX = pageWidth / 2 - logoWidth / 2;
          const logoY = pageHeight - 90; // 稍微上移一点
          pdf.addImage(base64Logo, 'PNG', logoX, logoY, logoWidth, logoHeight);
        }

// 贵州省高等学校智能计算与预警监测创新团队 (底部左侧)
        pdf.setFontSize(10);
        pdf.text('贵州省高等学校智能计算与预警监测创新团队', 70, pageHeight - 55); // 稍微上移一点

// 贵州省高等学校电力装备制造质量智能化评价与预警创新团队 (底部左侧，上一行下方)
        pdf.text('贵州省高等学校电力装备制造质量智能化评价与预警创新团队', 60, pageHeight - 48); // 稍微上移一点

// 二〇二五年四月 (底部右侧)
        pdf.text('二〇二五年四月', pageWidth - 100, pageHeight - 30, {align: 'center'}); // 稍微上移一点


        // --- 添加第二页 (指标评估明细) ---
        pdf.addPage();
        startY = 15; // Reset startY for the new page

        pdf.setFontSize(18);
        pdf.text(reportTitle, pdf.internal.pageSize.getWidth() / 2, startY, {align: 'center'});
        startY += 10;

        pdf.setFontSize(10);
        pdf.text(generationTime, 14, startY);
        pdf.text(reportCodeText, pdf.internal.pageSize.getWidth() - 14, startY, {align: 'right'});
        startY += 5;
        pdf.text(deviceModelText, 14, startY);
        startY += 5;
        pdf.text(originalPriceText, 14, startY);
        startY += 8;

        pdf.line(14, startY, pdf.internal.pageSize.getWidth() - 14, startY);
        startY += 8;

        pdf.setFontSize(14);
        pdf.text('指标评估明细', 14, startY);
        startY += 6;

        const indicatorHead = [[
          '一级指标', '二级指标', '测定值', '单位', '评估值', '一级权重', '二级权重', '加权权重', '加权得分'
        ]];
        const indicatorBody = this.secondaryIndicators.map(ind => [
          ind.primaryIndicator,
          ind.name,
          this.scores[ind.name] ?? '-',
          ind.unit || '分',
          this.normalizedValues[ind.name]?.toFixed(4) || '-',
          this.primaryIndicatorWeights[ind.primaryIndicator]?.toFixed(4),
          ind.weight?.toFixed(4),
          ind.weightedWeight?.toFixed(4) || '-',
          this.weightedScores[ind.name]?.toFixed(4) || '-',
        ]);

        pdf.autoTable({
          startY: startY,
          head: indicatorHead,
          body: indicatorBody,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei'},
          styles: {fontSize: 7, cellPadding: 1, font: 'simhei', fontStyle: 'normal'},
          columnStyles: {
            0: {cellWidth: 15}, 1: {cellWidth: 40}, 2: {cellWidth: 15}, 3: {cellWidth: 10},
            4: {cellWidth: 18}, 5: {cellWidth: 18}, 6: {cellWidth: 18}, 7: {cellWidth: 18},
            8: {cellWidth: 18},
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }
        });

        startY = pdf.lastAutoTable.finalY + 10;

        pdf.line(14, startY, pdf.internal.pageSize.getWidth() - 14, startY);
        startY += 8;

        pdf.setFontSize(14);
        pdf.text('总得分与评估等级', 14, startY);
        startY += 6;

        pdf.setFontSize(10);
        pdf.text(`总得分: ${this.totalScore ? this.totalScore.toFixed(4) : '-'}`, 14, startY);
        startY += 5;
        let gradeText = `装备状态: ${this.grade || '-'}级`;
        pdf.text(gradeText, 14, startY);
        startY += 8;

        pdf.line(14, startY, pdf.internal.pageSize.getWidth() - 14, startY);
        startY += 8;

        pdf.setFontSize(14);
        pdf.text('装备剩余价值', 14, startY);
        startY += 6;
        pdf.setFontSize(12);
        let price = ` ${this.finalRealPrice !== null ? this.finalRealPrice.toFixed(2) : '-'} 元`;
        pdf.text(price, 14, startY);
        startY += 10;

        pdf.line(14, startY, pdf.internal.pageSize.getWidth() - 14, startY);
        startY += 8;

        pdf.setFontSize(14);
        pdf.text('评价结果判定标准', 14, startY);
        startY += 6;

        const criteriaHead = [[
          '计算结果区间', '装备状态等级', '建议剩余价值 (原价格百分比)'
        ]];
        const criteriaBody = [
          ['[0.85, 1]', 'A 级', '85%'],
          ['[0.70, 0.85)', 'B 级', '60%'],
          ['[0.50, 0.70)', 'C 级', '30%'],
          ['[0.30, 0.50)', 'D 级', '15%'],
          ['[0.10, 0.30)', 'E 级', '10%'],
          ['(0, 0.10)', 'F 级', '5%'],
          ['0', '建议报废', '0% (或按报废处理)']
        ];

        pdf.autoTable({
          startY: startY,
          head: criteriaHead,
          body: criteriaBody,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei', halign: 'center'},
          styles: {fontSize: 9, cellPadding: 2, font: 'simhei', fontStyle: 'normal'},
          columnStyles: {
            0: {halign: 'center', cellWidth: 40},
            1: {halign: 'center', cellWidth: 40},
            2: {halign: 'center', cellWidth: 60}
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }

        });

        const marginBottom = 10;
        const footerStartX = pageWidth - 90;
        let footerY = pageHeight - marginBottom;
        const lineHeight = 4;

        pdf.setFontSize(8);
        pdf.setTextColor(100);

        const line4 = '地址: 贵州省花溪大学城贵州财经大学 邮编: 550025';
        pdf.text(line4, footerStartX, footerY);
        footerY -= lineHeight;

        const line3 = '联系电话: 13595041920';
        pdf.text(line3, footerStartX, footerY);
        footerY -= lineHeight;

        const line2 = '版权所有: 贵州财经大学';
        pdf.text(line2, footerStartX, footerY);
        footerY -= lineHeight;

        const line1 = '技术支持: 贵州省高等学校智能计算与预警监测创新团队';

        pdf.text(line1, footerStartX, footerY);

        // --- 添加第三页 (表1 电力装备巡检价值评估体系和评分标准 以及 表2 指标权重) ---
        pdf.addPage();
        startY = 15; // Reset startY for the new page

        // --- 表1：电力装备巡检价值评估体系和评分标准 ---
        pdf.setFontSize(16);
        pdf.text('表1 电力装备巡检价值评估体系和评分标准', pdf.internal.pageSize.getWidth() / 2, startY, {align: 'center'});
        startY += 10;

        const indicatorHead5_1 = [
          ['一级指标', '二级指标', '指标阐释', '评分阶段', '指标类型']
        ];
        const indicatorBody5_1 = [
          ['基础检查 (A1)', '外观状况 (B1)', '考察装备外观情况，例如毛刺、锈蚀、污迹等', '最大值：100 分；最小值：0 分', '正向'],
          ['', '发货及合同等材料完整情况 (B2)', '考察装备从购买直至当前为止的所有材料完整性，包括合同、发货单等', '最大值：100 分；最小值：0 分', '正向'],
          ['', '装配工艺 (B3)', '考量装备安装过程中的装配工艺情况，例如结构件紧固情况、螺丝紧固情况及焊接核查的一致性等', '最大值：100 分；最小值：0 分', '正向'],
          ['', '电气性能 (B4)', '通过电气试验，考察装备电气性能是否完好，例如雷电冲击、局放等', '最大值：100 分；最小值：0 分', '正向'],
          ['', '机械性能 (B5)', '通过机械试验，考察装备机械性能是否完好，例如断路器 200 次机械操作试验、变压器振动控制、冷却水平等', '最大值：100 分；最小值：0 分', '正向'],
          ['运行性能 (A2)', '运行时长 (B6)', '装备的各项性能随着运行时间的增长逐步衰减、老化', '最大运行年限：20 年；最小运行年限：0 年', '负向'],
          ['', '故障率 (B7)', '考察装备运行中发生的故障情况', '最大值：10%；最小值：0%', '负向'],
          ['', '缺陷率 (B8)', '考察装备运行中发生的缺陷情况，例如漏油、局放等', '最大值：20%；最小值：0%', '负向'],
          ['品牌声誉 (A3)', '市场占有率 (B9)', '考察装备制造厂家的市场占有情况', '最大值：100%；最小值：0%', '正向'],
          ['', '历史履约情况 (B10)', '考察装备制造厂家在本单位的历史履约情况', '最大值：100 分；最小值：0 分', '正向'],
        ];

        pdf.autoTable({
          startY: startY,
          head: indicatorHead5_1,
          body: indicatorBody5_1,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei', halign: 'center'},
          styles: {
            fontSize: 9,
            cellPadding: 2,
            font: 'simhei',
            fontStyle: 'normal',
            halign: 'center',
            valign: 'middle'
          },
          columnStyles: {
            0: {cellWidth: 25}, // 一级指标
            1: {cellWidth: 40}, // 二级指标
            2: {cellWidth: 60}, // 指标阐释
            3: {cellWidth: 35}, // 评分阶段
            4: {cellWidth: 20}  // 指标类型
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }
        });

        startY = pdf.lastAutoTable.finalY + 10;

        // --- 表2：指标权重 ---
        pdf.setFontSize(14);
        pdf.text('1.2 权重确立', 14, startY);
        startY += 6;
        pdf.text('表2 指标权重', pdf.internal.pageSize.getWidth() / 2, startY, {align: 'center'});
        startY += 10;

        const indicatorHead5_2 = [
          ['序号', '一级指标', '权重', '序号', '二级指标', '权重', '加权权重']
        ];
        const indicatorBody5_2 = [
          ['1', '基础检查 (A1)', '0.2453', '1', '外观状况 (B1)', '0.3313', '0.0813'],
          ['', '', '', '2', '发货及合同等材料完整情况 (B2)', '0.2895', '0.0710'],
          ['', '', '', '3', '装配工艺 (B3)', '0.3792', '0.0930'],
          ['2', '运行性能 (A2)', '0.4299', '4', '电气性能 (B4)', '0.1987', '0.0854'],
          ['', '', '', '5', '机械性能 (B5)', '0.1833', '0.0788'],
          ['', '', '', '6', '运行时长 (B6)', '0.1690', '0.0727'],
          ['', '', '', '7', '故障率 (B7)', '0.2336', '0.1004'],
          ['', '', '', '8', '缺陷率 (B8)', '0.2154', '0.0926'],
          ['3', '品牌声誉 (A3)', '0.3248', '9', '市场占有率 (B9)', '0.3958', '0.1286'],
          ['', '', '', '10', '历史履约情况 (B10)', '0.6042', '0.1962']
        ];

        pdf.autoTable({
          startY: startY,
          head: indicatorHead5_2,
          body: indicatorBody5_2,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei', halign: 'center'},
          styles: {
            fontSize: 9,
            cellPadding: 2,
            font: 'simhei',
            fontStyle: 'normal',
            halign: 'center',
            valign: 'middle'
          },
          columnStyles: {
            0: {cellWidth: 10}, // 序号 (左侧)
            1: {cellWidth: 30}, // 一级指标
            2: {cellWidth: 20}, // 权重 (左侧)
            3: {cellWidth: 20}, // 序号 (右侧)
            4: {cellWidth: 55}, // 二级指标
            5: {cellWidth: 30}, // 权重 (右侧)
            6: {cellWidth: 30}  // 加权权重
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }
        });

        startY = pdf.lastAutoTable.finalY + 10;

        // --- 添加第四页 (装备状态确认方法) ---
        pdf.addPage();
        let startY_page4 = 15; // Explicitly declare startY for the fourth page

        pdf.setFontSize(16);
        pdf.text('5 装备状态确认方法', 14, startY_page4);
        startY_page4 += 10;

// 5.1 正向指标归一化处理
        pdf.setFontSize(14);
        pdf.text('5.1 正向指标归一化处理', 14, startY_page4);
        startY_page4 += 8;

        pdf.setFontSize(12);
        pdf.text('见式（1）', 14, startY_page4);
        startY_page4 += 6;

// 公式 (1)
        pdf.setFontSize(16);
        const formula1_part1 = 'R(Xᵢ) = (Xᵢ - Xmin) / (Xmax - Xmin)';
        pdf.text(formula1_part1, 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 10;

        pdf.setFontSize(12);
        pdf.text('式中：', 14, startY_page4);
        startY_page4 += 6;
        pdf.text('R(Xᵢ) 表示某指标的评估值，Xᵢ 表示该指标的测定值；', 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 6;
        pdf.text('Xmax 表示该指标的最大值；', 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 6;
        pdf.text('Xmin 表示该指标的最小值。', 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 12;

// 5.2 负向指标归一化处理
        pdf.setFontSize(14);
        pdf.text('5.2 负向指标归一化处理', 14, startY_page4);
        startY_page4 += 8;

        pdf.setFontSize(12);
        pdf.text('见式（2）', 14, startY_page4);
        startY_page4 += 6;

// 公式 (2)
        pdf.setFontSize(16);
        const formula2_part1 = 'R(Xᵢ) = 1 - (Xᵢ - Xmin) / (Xmax - Xmin)';
        pdf.text(formula2_part1, 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 10;

        pdf.setFontSize(12);
        pdf.text('式中：', 14, startY_page4);
        startY_page4 += 6;
        pdf.text('R(Xᵢ) 表示某指标的评估值，Xᵢ 表示该指标的测定值；', 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 6;
        pdf.text('Xmax 表示该指标的最大值；', 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 6;
        pdf.text('Xmin 表示该指标的最小值。', 14, startY_page4, {maxWidth: pageWidth - 28});
        startY_page4 += 12;

// 5.3 各指标（见表1）分值 Sa 为 R(Xi) 与每项指标的加权权重相乘得到。
        pdf.setFontSize(14);
        pdf.text('5.3 各指标（见表1）分值 Sa 为 R(Xᵢ) 与每项指标的加权权重相乘得到。', 14, startY_page4);
        startY_page4 += 8;

        pdf.setFontSize(12);
        pdf.text('见式（3）', 14, startY_page4);
        startY_page4 += 6;

// 公式 (3)
        pdf.setFontSize(16);
        const formula3_part1 = '总得分 S = ';
        const formula3_sum = '∑';
        const formula3_subscript = 'ᵢ=1';
        const formula3_superscript = 'n';
        const formula3_part2 = ' S';
        const formula3_subscript_a = 'aᵢ';
        const formula3_condition = ', i = 1, 2, ..., n。';

        let formula3_x = 14;
        pdf.text(formula3_part1, formula3_x, startY_page4);
        formula3_x += pdf.getTextWidth(formula3_part1);

        pdf.setFontSize(20); // 稍微放大求和符号
        pdf.text(formula3_sum, formula3_x, startY_page4 + 2); // 调整垂直位置
        formula3_x += pdf.getTextWidth(formula3_sum);

        pdf.setFontSize(10); // 缩小上下标
        pdf.text(formula3_subscript, formula3_x - pdf.getTextWidth(formula3_sum) + 2, startY_page4 + 8); // 调整位置
        pdf.text(formula3_superscript, formula3_x - pdf.getTextWidth(formula3_sum) + 2, startY_page4 - 4); // 调整位置

        pdf.setFontSize(16); // 恢复字体大小
        pdf.text(formula3_part2, formula3_x, startY_page4);
        formula3_x += pdf.getTextWidth(formula3_part2);

        pdf.setFontSize(10);
        pdf.text(formula3_subscript_a, formula3_x - pdf.getTextWidth(formula3_part2) + 5, startY_page4 + 6);

        pdf.setFontSize(12);
        pdf.text(formula3_condition, formula3_x + 5, startY_page4);

        startY_page4 += 10;

        // --- 添加第五页 (附录 A 实例计算过程) ---
        pdf.addPage();
        let startY_page5 = 15; // Reset startY for the new page
        // const pageWidth = pdf.internal.pageSize.getWidth();

        pdf.setFontSize(16);
        pdf.text('附录 A', pdf.internal.pageSize.getWidth() / 2, startY_page5, {align: 'center'});
        startY_page5 += 8;
        pdf.setFontSize(16);
        pdf.text('实例计算过程', pdf.internal.pageSize.getWidth() / 2, startY_page5, {align: 'center'});
        startY_page5 += 15;

        // A.1 确定评估对象
        pdf.setFontSize(14);
        pdf.text('A.1 确定评估对象', 14, startY_page5);
        startY_page5 += 8;

        pdf.setFontSize(12);
        const paragraph1 = '选取某公司已实际进行拍卖处理的 3 台配套变压器为例，利用本标准提出的方法进行剩余价值评估。配套参数情况如表 A.1 所示：';
        const splitParagraph1 = pdf.splitTextToSize(paragraph1, pageWidth - 28);
        pdf.text(splitParagraph1, 14, startY_page5);
        startY_page5 += pdf.getTextDimensions(splitParagraph1).h + 8;

        // 表A.1 配套参数情况
        pdf.setFontSize(14);
        pdf.text('表A.1 配套参数情况', pdf.internal.pageSize.getWidth() / 2, startY_page5, {align: 'center'});
        startY_page5 += 10;

        const appendixHead1 = [
          ['影响因素', '配套1', '配套2', '配套3']
        ];
        const appendixBody1 = [
          ['型号', 'S9-S/10', 'S9-30/10', 'S11-M-50/10'],
          ['原价（元）', '22420', '45580', '62590'],
          ['实际拍卖价值（元）', '1358.64', '2830.50', '3453.21'],
          ['外观状况（B1）', '30分', '35分', '40分'],
          ['发货及合同等材料完整情况（B2）', '80分', '75分', '90分'],
          ['装配工艺（B3）', '80分', '78分', '85分'],
          ['电气性能（B4）', '25分', '30分', '38分'],
          ['机械性能（B5）', '30分', '45分', '40分'],
          ['运行时长（B6）', '20年', '20年', '20年'],
          ['故障率（B7）', '4.5%', '3.1%', '4.8%'],
          ['缺陷率（B8）', '14.2%', '3.7%', '16.3%'],
          ['市场占有率（B9）', '15%', '30%', '35%'],
          ['历史履约情况（B10）', '85分', '75分', '70分'],
        ];

        pdf.autoTable({
          startY: startY_page5,
          head: appendixHead1,
          body: appendixBody1,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei', halign: 'center'},
          styles: {
            fontSize: 9,
            cellPadding: 2,
            font: 'simhei',
            fontStyle: 'normal',
            halign: 'center',
            valign: 'middle'
          },
          columnStyles: {
            0: {cellWidth: 60}, // 影响因素
            1: {cellWidth: 45}, // 配套1
            2: {cellWidth: 45}, // 配套2
            3: {cellWidth: 45}  // 配套3
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }
        });

        startY_page5 = pdf.lastAutoTable.finalY + 15;

        // A.2 指标规范化处理
        pdf.setFontSize(14);
        pdf.text('A.2 指标规范化处理', 14, startY_page5);
        startY_page5 += 8;

        pdf.setFontSize(12);
        const paragraph2 = '对于正向指标通过式（1）计算，对于负向指标通过式（2）计算，规范化结果如表 A.2 所示。';
        const splitParagraph2 = pdf.splitTextToSize(paragraph2, pageWidth - 28);
        pdf.text(splitParagraph2, 14, startY_page5);
        startY_page5 += pdf.getTextDimensions(splitParagraph2).h + 8;

        // 表A.2 指标规范化值
        pdf.setFontSize(14);
        pdf.text('表A.2 指标规范化值', pdf.internal.pageSize.getWidth() / 2, startY_page5, {align: 'center'});
        startY_page5 += 10;

        const appendixHead2 = [
          ['影响因素', '配套1', '配套2', '配套3']
        ];
        const appendixBody2 = [
          ['外观状况（B1）', '0.3000', '0.3500', '0.4000'],
          ['发货及合同等材料完整情况（B2）', '0.8000', '0.7500', '0.9000'],
          ['装配工艺（B3）', '0.8000', '0.7800', '0.8500'],
          ['电气性能（B4）', '0.2500', '0.3000', '0.3800'],
          ['机械性能（B5）', '0.3000', '0.4500', '0.4000'],
          ['运行时长（B6）', '0.0000', '0.0000', '0.0000'],
          ['故障率（B7）', '0.5500', '0.6900', '0.5200'],
          ['缺陷率（B8）', '0.2900', '0.8150', '0.1850'],
          ['市场占有率（B9）', '0.1500', '0.3000', '0.3500'],
          ['历史履约情况（B10）', '0.8500', '0.7500', '0.7000'],
        ];

        pdf.autoTable({
          startY: startY_page5,
          head: appendixHead2,
          body: appendixBody2,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei', halign: 'center'},
          styles: {
            fontSize: 9,
            cellPadding: 2,
            font: 'simhei',
            fontStyle: 'normal',
            halign: 'center',
            valign: 'middle'
          },
          columnStyles: {
            0: {cellWidth: 60}, // 影响因素
            1: {cellWidth: 45}, // 配套1
            2: {cellWidth: 45}, // 配套2
            3: {cellWidth: 45}  // 配套3
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }
        });

        startY_page5 = pdf.lastAutoTable.finalY + 15;

        // A.3 计算结果确定
        pdf.setFontSize(14);
        pdf.text('A.3 计算结果确定', 14, startY_page5);
        startY_page5 += 8;

        pdf.setFontSize(12);
        const paragraph3 = '将表 A.2 中各指标的规范化值与表 2 中对应的“加权权重”值相乘，得到每个二级指标的计算结果，再将其全部进行相加，得到整体计算结果，如表 A.3 所示。';
        const splitParagraph3 = pdf.splitTextToSize(paragraph3, pageWidth - 28);
        pdf.text(splitParagraph3, 14, startY_page5);
        startY_page5 += pdf.getTextDimensions(splitParagraph3).h + 8;

        startY_page5 = pdf.lastAutoTable.finalY + 15; // 紧接第五页的 startY

        // 表A.3 计算结果确定
        pdf.setFontSize(14);
        pdf.text('表 A.3 计算结果确定', pdf.internal.pageSize.getWidth() / 2, startY_page5, {align: 'center'});
        startY_page5 += 10;
        startY_page5 += 10;
        startY_page5 += 10;

        const appendixHead3 = [
          ['影响因素', '配套1', '配套2', '配套3']
        ];
        const appendixBody3 = [
          ['外观状况（B1）', '0.0244', '0.0285', '0.0325'],
          ['发货及合同等材料完整情况（B2）', '0.0568', '0.0533', '0.0639'],
          ['装配工艺（B3）', '0.0744', '0.0725', '0.0791'],
          ['电气性能（B4）', '0.0214', '0.0256', '0.0325'],
          ['机械性能（B5）', '0.0236', '0.0355', '0.0315'],
          ['运行时长（B6）', '0.0000', '0.0000', '0.0000'],
          ['故障率（B7）', '0.0552', '0.0693', '0.0522'],
          ['缺陷率（B8）', '0.0269', '0.0755', '0.0171'],
          ['市场占有率（B9）', '0.0193', '0.0386', '0.0450'],
          ['历史履约情况（B10）', '0.1668', '0.1472', '0.1373'],
          ['整体计算结果', '0.4687', '0.5458', '0.4911'],
        ];

        pdf.autoTable({
          startY: startY_page5,
          head: appendixHead3,
          body: appendixBody3,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei', halign: 'center'},
          styles: {
            fontSize: 9,
            cellPadding: 2,
            font: 'simhei',
            fontStyle: 'normal',
            halign: 'center',
            valign: 'middle'
          },
          columnStyles: {
            0: {cellWidth: 70}, // 影响因素
            1: {cellWidth: 35}, // 配套1
            2: {cellWidth: 35}, // 配套2
            3: {cellWidth: 35}  // 配套3
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }
        });

        startY_page5 = pdf.lastAutoTable.finalY + 15;

        // A.4 评价结果判定
        pdf.setFontSize(14);
        pdf.text('A.4 评价结果判定', 14, startY_page5);
        startY_page5 += 8;

        pdf.setFontSize(12);
        const paragraph4 = '根据整体计算结果，通过“7 评价结果判定”的规定，可确定 3 台配套变压器的状态等级及剩余价值，如表 A.4 所示。';
        const splitParagraph4 = pdf.splitTextToSize(paragraph4, pageWidth - 28);
        pdf.text(splitParagraph4, 14, startY_page5);
        startY_page5 += pdf.getTextDimensions(splitParagraph4).h + 8;

        // 表A.4 评价结果判定
        pdf.setFontSize(14);
        pdf.text('表 A.4 评价结果判定', pdf.internal.pageSize.getWidth() / 2, startY_page5, {align: 'center'});
        startY_page5 += 10;

        const appendixHead4 = [
          ['价值确认', '配套1', '配套2', '配套3']
        ];
        const appendixBody4 = [
          ['装备状态', '0.4687 (D级)', '0.5458 (C级)', '0.4911 (D级)'],
          ['装备剩余价值（元）', '3363.00', '13674.00', '9388.50'],
        ];

        pdf.autoTable({
          startY: startY_page5,
          head: appendixHead4,
          body: appendixBody4,
          theme: 'grid',
          headStyles: {fillColor: [220, 220, 220], textColor: 0, fontStyle: 'bold', font: 'simhei', halign: 'center'},
          styles: {
            fontSize: 12,
            cellPadding: 2,
            font: 'simhei',
            fontStyle: 'normal',
            halign: 'center',
            valign: 'middle'
          },
          columnStyles: {
            0: {cellWidth: 60}, // 价值确认
            1: {cellWidth: 45}, // 配套1
            2: {cellWidth: 45}, // 配套2
            3: {cellWidth: 45}  // 配套3
          },
          didDrawPage: () => {
            pdf.setFont('simhei');
          }
        });

        startY_page5 = pdf.lastAutoTable.finalY + 15;

        pdf.save(`评估报告-${this.reportCode}.pdf`);
      } catch (error) {
        console.error("生成 PDF 时出错:", error);
        alert("生成 PDF 报告失败，可能是字体加载问题或数据错误。请稍后重试或联系管理员。");
      }

    },
    //根据主要指标过滤次要指标
    filteredSecondaryIndicators(primaryIndicator) {
      return this.secondaryIndicators.filter(indicator => indicator.primaryIndicator === primaryIndicator);
    },
    goToUserDashboard() {
      router.push('/dashboard')
    }

  },
};
</script>

<style scoped>
/* --- Keep existing styles not related to progress bar --- */


#report-content {
  font-size: 20px;
}

#report-content h1,
#report-content h2 {
  text-align: center;
  margin-bottom: 15px;
}

#report-content table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

#report-content th,
#report-content td {
  border: 1px solid #ddd;
  padding: 6px;
  text-align: left;
  font-size: 0.85em;
  word-wrap: break-word;
  vertical-align: top;
}

#report-content th {
  background-color: #f2f2f2;
  font-weight: bold;
}

.grade-badge {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-size: 14px;
  font-weight: bold;
  color: white;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
}

#report-content p,
#report-content h2 {
  font-size: 1rem;
}

#report-content .text-h5 {
  font-size: 1.1rem;
  font-weight: bold;
}

.app-footer {
  background-color: #cbd8e8;
  color: black;
  padding: 20px 0;
}


.indicator-card {
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.indicator-row {
  display: flex;
}

.indicator-card :deep(.v-card-text) {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

.error-label {
  color: red !important;
}

.error-input {
  border-color: red !important;
}

.error-message {
  color: red;
  font-size: 0.8em;
  margin-top: 2px;
}


.modern-progress-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0 20px; /* 上下内边距 */
}

/* 进度条轨道 */
.progress-bar-modern {
  background: rgba(0, 0, 10, 0.7) url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><g fill="%231f1f3a" fill-opacity="0.4"><circle cx="50" cy="50" r="1"/><circle cx="10" cy="10" r="1"/><circle cx="90" cy="90" r="1"/><circle cx="10" cy="90" r="1"/><circle cx="90" cy="10" r="1"/><circle cx="30" cy="70" r="1"/><circle cx="70" cy="30" r="1"/><circle cx="30" cy="30" r="1.5"/><circle cx="70" cy="70" r="1.5"/></g></svg>'); /* 微妙的星空背景 */
  border-radius: 50px; /* 胶囊形状 */
  width: 95%; /* 稍宽一点 */
  height: 20px; /* 更粗的条 */
  overflow: hidden; /* 保持填充物在内部 */
  position: relative;
  box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.8), 0 0 8px rgba(74, 0, 224, 0.4); /* 更深的内阴影 + 外部辉光 */
  border: 1px solid rgba(74, 0, 224, 0.6); /* 稍强的边框 */
}

/* 填充部分的流动能量动画 */
@keyframes energyFlowFill {
  0% {
    background-position: -300px 0;
  }
  /* 渐变起始位置 */
  100% {
    background-position: calc(100% + 300px) 0;
  }
  /* 渐变结束位置 */
}

.progress-fill-modern {
  /* 强烈的、流动的能量束渐变 */
  background: linear-gradient(
      90deg,
      rgba(142, 45, 226, 0.6) 0%, /* 紫色淡入 */ #bd00ff 40%, /* 强烈的紫/品红 */ #00d4ff 60%, /* 强烈的青色 */ rgba(0, 212, 255, 0.6) 100% /* 青色淡出 */
  );
  background-size: 400px 100%; /* 控制动画图案的宽度 */
  height: 100%;
  border-radius: 50px; /* 匹配轨道形状 */
  position: relative; /* 对加载图标定位至关重要 */
  animation: energyFlowFill 2.2s linear infinite; /* 流动速度 */
  /* --- 这行被修改了 --- */
  transition: width 0.1s linear; /* 匀速线性宽度变化 */
  /* --- 修改结束 --- */
  box-shadow: 0 0 12px #bd00ff, 0 0 22px #00d4ff, inset 0 0 6px rgba(255, 255, 255, 0.4); /* 双色辉光 + 内部高光 */
  overflow: visible; /* 允许加载图标稍微超出填充边界 */
}

/* 定位加载图标容器 */
.loading-spinner {
  position: absolute;
  /* 动态定位在填充部分的末端（右侧） */
  /* 'left' 样式在模板中动态设置，我们调整相对定位 */
  right: -10px; /* 定位在右边缘稍微*过去*一点的位置 */
  top: 50%;
  transform: translateY(-50%); /* 垂直居中 */
  width: auto; /* 根据内容调整宽度 */
  height: 28px; /* 更高的加载图标区域 */
  display: flex;
  align-items: center;
  filter: drop-shadow(0 0 5px #fff); /* 给加载图标组添加辉光 */
  /* 关键：覆盖模板中的内联 left 样式 */
  left: auto !important;
}

/* 将单个加载点设置为发光的能量粒子 */
@keyframes energyPulse {
  0%, 100% {
    transform: scale(0.7);
    box-shadow: 0 0 5px #fff, 0 0 10px #00d4ff, 0 0 15px #bd00ff;
    opacity: 0.7;
  }
  50% {
    transform: scale(1.1);
    box-shadow: 0 0 8px #fff, 0 0 15px #00d4ff, 0 0 25px #bd00ff;
    opacity: 1;
  }
}

.spinner-dot {
  width: 10px; /* 更大的点 */
  height: 10px;
  background-color: #ffffff; /* 亮白色核心 */
  border-radius: 50%;
  margin: 0 4px; /* 点之间更大的间距 */
  animation: energyPulse 1.3s cubic-bezier(0.5, 0, 0.5, 1) infinite;
  box-shadow: 0 0 5px #fff, 0 0 10px #00d4ff, 0 0 15px #bd00ff; /* 三重辉光 */
}

/* 错开点的动画 */
.spinner-dot:nth-child(1) {
  animation-delay: -0.26s;
}

.spinner-dot:nth-child(2) {
  animation-delay: -0.13s;
}

.spinner-dot:nth-child(3) {
  animation-delay: 0s;
}

/* 进度百分比文字样式 */
.progress-text-modern {
  margin-top: 18px; /* 进度条下方更多空间 */
  font-size: 1.3em; /* 更大的文字 */
  color: #ffffff;
  font-weight: bold;
  text-shadow: 0 0 5px #00d4ff, 0 0 10px #bd00ff; /* 匹配辉光颜色 */
  letter-spacing: 1px; /* 轻微字间距 */
}

/* --- 其他现有样式 (.indicator-card 等) --- */
.indicator-card {
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.indicator-row {
  display: flex;
}


.app-footer {
  background-color: #cbd8e8;
  color: black;
  padding: 20px 0;
}
</style>